package com.traffic.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Multimap;
import com.traffic.annotation.ApiJsonObject;
import com.traffic.annotation.ApiJsonProperty;
import com.traffic.constant.Status;
import com.traffic.entity.*;

import com.traffic.exception.BaseException;
import com.traffic.model.ApiResponse;

import com.traffic.model.MyDeltRankResult;
import com.traffic.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.google.common.collect.TreeMultimap;

import java.text.ParseException;
import java.util.*;

@Api(tags = "排行榜名次相关接口")
@RestController
@RequestMapping(value = "/leaderboard")
@Slf4j
public class LeaderboardController {

    @Autowired
    LeaderboardService leaderboardService;

    @Autowired
    LeaderboardpreService leaderboardpreService;

    @Autowired
    RankService rankService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    ResourceService resourceService;

    @Autowired
    FriendService friendService;


    @ApiOperation(value = "【排行榜】", notes = "获得排行榜")
    @PostMapping("/getrank")
    @ApiJsonObject(name = "rank",value = {
            @ApiJsonProperty(type =String.class,key = "ranktype",example = "his_mileage（单项） 或score（综合）" , description = "排行项目名称"),
            @ApiJsonProperty(type =String.class,key = "user_id",example = "12" , description = "当前用户id"),

    })
    public ApiResponse getRank(@RequestBody Map<String, String> param) {

        String rtype = param.get("ranktype");
        Long user_id = Long.parseLong(param.get("user_id"));

        List<Object> led = leaderboardService.queryTargetLeaderboard(rtype);

        List<ReturnRank> returnRanks = new ArrayList<>();

        int j = 1;
        for(Object l :led){
            ReturnRank temp = new ReturnRank();
            temp.setOrder(j);

            UserInfo usi = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id",l));

            temp.setNickname(usi.getNickName());
            Double data = Double.parseDouble(StringUtils.strip(rankService.selectTargetObject(l,rtype).toString(),"[]"));
            temp.setData(data);

            Long uid = Long.parseLong(l.toString());

            temp.setUserid(uid);

            Integer isfriend = friendService.isFriend(user_id,uid);
            temp.setIsfriend(isfriend);

            Object myrank = leaderboardService.queryMyTypeRank(rtype,uid);
            if (ObjectUtils.isEmpty(myrank))temp.setDeltorder(0);
            else {
                Object prerank = leaderboardpreService.queryTypeRank(rtype,uid);
                if(ObjectUtils.isEmpty(prerank)){
                    temp.setDeltorder(0);
                }
                else{
                    Integer rank1 = Integer.parseInt(StringUtils.strip(prerank.toString(),"[]"));
                    Integer rank2 = Integer.parseInt(StringUtils.strip(myrank.toString(),"[]"));
                    temp.setDeltorder(rank1-rank2);
                }
            }

            String img = resourceService.getImgUrl(usi.getHeadImg());
            temp.setHeadimg(img);


            returnRanks.add(temp);
            j++;
            //temp.setData();
        }

        return ApiResponse.ofStatus(Status.OK, returnRanks);

    }


    @ApiOperation(value = "【排行榜】", notes = "获得自身排名")
    @PostMapping("/getmyrank")
    @ApiJsonObject(name = "myrank",value = {
            @ApiJsonProperty(type =String.class,key = "ranktype",example = "his_mileage（单项） 或score（综合）" , description = "排行项目名称"),
            @ApiJsonProperty(type =String.class,key = "user_id",example = "123" , description = "用户id"),

    })
    public ApiResponse getmyRank(@RequestBody Map<String, String> param) {

        String type = param.get("ranktype");
        Long userid = new Long(param.get("user_id"));
        MyDeltRankResult result = new MyDeltRankResult();

        Object myrank = leaderboardService.queryMyTypeRank(type,userid);

        if(ObjectUtils.isEmpty(myrank)){
            result.setRank("-1");
            result.setDeltrank("-1");
            result.setMileage(0.0);
            return ApiResponse.ofStatus(Status.OK, result);
        }
        Integer rank2 = Integer.parseInt(StringUtils.strip(myrank.toString(),"[]"));
        result.setRank(rank2.toString());
        Object prerank = leaderboardpreService.queryTypeRank(type,userid);

        if(ObjectUtils.isEmpty(prerank)){

            result.setDeltrank("-1");
            result.setMileage(0.0);
            return ApiResponse.ofStatus(Status.OK, result);
        }

        Integer rank1 = Integer.parseInt(StringUtils.strip(prerank.toString(),"[]"));
        Integer delt = rank1-rank2;
        result.setDeltrank(delt.toString());

        QueryWrapper<Rank> wrapper = new QueryWrapper<>();
        Rank  rank = rankService.selectByUserId(userid);
        result.setMileage(rank.getHisMileage());

        return ApiResponse.ofStatus(Status.OK, result);

    }


    @ApiOperation(value = "【排行榜】", notes = "名次升降")
    @PostMapping("/comparerank")
    @ApiJsonObject(name = "myrank",value = {
            @ApiJsonProperty(type =String.class,key = "ranktype",example = "his_mileage（单项） 或score（综合）" , description = "排行项目名称"),
            @ApiJsonProperty(type =String.class,key = "user_id",example = "123" , description = "用户id"),

    })
    public ApiResponse compareRank(@RequestBody Map<String, String> param) {

        String type = param.get("ranktype");
        Long userid = new Long(param.get("user_id"));

        Object myrank = leaderboardService.queryMyTypeRank(type,userid);

        if(ObjectUtils.isEmpty(myrank)){
            return ApiResponse.ofStatus(Status.OK, "未上榜");
        }

        Object prerank = leaderboardpreService.queryTypeRank(type,userid);

        if(ObjectUtils.isEmpty(prerank)){
            return ApiResponse.ofStatus(Status.OK, "上次未上榜");
        }

        Integer rank1 = Integer.parseInt(StringUtils.strip(prerank.toString(),"[]"));
        Integer rank2 = Integer.parseInt(StringUtils.strip(myrank.toString(),"[]"));

        return ApiResponse.ofStatus(Status.OK, rank1-rank2);

    }


    @ApiOperation(value = "【排行榜】", notes = "获得好友排行榜")
    @PostMapping("/getfriendrank")
    @ApiJsonObject(name = "rank",value = {
            @ApiJsonProperty(type =String.class,key = "ranktype",example = "his_mileage（单项） 或score（综合）" , description = "排行项目名称"),
            @ApiJsonProperty(type =String.class,key = "user_id",example = "12" , description = "当前用户id"),

    })
    public ApiResponse getFriendRank(@RequestBody Map<String, String> param) {

        String rtype = param.get("ranktype");
        Long user_id = Long.parseLong(param.get("user_id"));

        List<Long> friends = friendService.getFriend(user_id);

        List<Double> datas = new ArrayList<>();

        List<ReturnRank> returnRanks = new ArrayList<>();

        Multimap<Double,Long> map = TreeMultimap.create();

        friends.add(user_id);

        for(Long f :friends){

            Object temp = rankService.selectTargetObject(f,rtype);
            Double dt = Double.parseDouble(StringUtils.strip(temp.toString(),"[]"));
            datas.add(dt);
            map.put(dt,f);

        }
        System.out.println(map);

        Collections.sort(datas);
        Collections.reverse(datas);



        int j = 1;
        Double pred = -9999.0;
        Iterator preit=map.get(datas.get(0)).iterator();
        for (Double d: datas) {

            ReturnRank temp = new ReturnRank();
            temp.setOrder(j);
            Iterator nowit=map.get(d).iterator();
            if(d.doubleValue()==pred.doubleValue()){

                nowit = preit;
               // System.out.println(d);
            }

            Long uid = Long.parseLong(nowit.next().toString());
            UserInfo usi = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id",uid));

            temp.setNickname(usi.getNickName());
            temp.setData(d);
            temp.setUserid(uid);
            temp.setIsfriend(1);
            temp.setDeltorder(0);
            String img = resourceService.getImgUrl(usi.getHeadImg());
            temp.setHeadimg(img);

            returnRanks.add(temp);

            j++;
            pred = d;
            preit=nowit;
//            System.out.println(d);
//            System.out.println(pred);
        }



        return ApiResponse.ofStatus(Status.OK,returnRanks);

    }

}
